package org.example.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

/**
 * @Configurable 声明当前类就是Spring的配置类，用于替代 applicationContext.xml配置文件
 *
 * @ComponentScan  替代  <context:component-scan base-package="org.example"/>
 *
 *
 *  @PropertySource("classpath:db.properties") 替代    <context:property-placeholder location="classpath:db.properties"/>
 */
@Configurable
//@ComponentScan(basePackages = {"org.example.controller","org.example.service","org.example.dao"})
//@ComponentScan(basePackages = {"org.example"})
//@ComponentScan(value = {"org.example"})

@ComponentScan("org.example")
@PropertySource("classpath:db.properties")
public class SpringConfig {


    /*
    *  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!--
            使用 SpringEL 语法  Spring Expression Language
            ${db.properties配置文件中的名称} 读取对应的值
            注意：Spring默认读取的username是操作系统当前的账号
            所以db.properties的 账号不能使用username
            建议：该一个名称或者同意使用一个前缀
        -->
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
    </bean>
    *
    * @Bean注解相当于xml配置bean
    *  方法名称默认就是bean的id
    *  属性说明
    *   name：设置bean的id
    *
    * */

    /**
     * @Value 读取 xxx.properties配置文件中名称对应的值
     */

    @Value("${jdbc.driverClassName}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.maxActive}")
    private Integer maxActive;


    @Bean(name = "dataSource",initMethod = "init",destroyMethod = "close")
    public DruidDataSource getDataSource() {
        System.out.println("SpringConfig.getDataSource");
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setMaxActive(maxActive);
        return druidDataSource;
    }
}
